package com.example.zx.theline.zsjh;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.zx.theline.R;
import com.example.zx.theline.zsjh.pub.ZsyjhChaKanActivity;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.ShyjhxqBean;
import GsonBean.ZsyjhBean;
import GsonBean.ZsyjhxxBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import Utils.RefreshManager;
import app.MyApplication;
import base.BaseFragment;
import bean.SearchBean;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.ZsyjhSearchView;

/**
 * Created by Ren on 2017/7/24.
 * 正式月计划
 */

public class ZsyjhFragment extends BaseFragment implements SHSwipeRefreshLayout.SHSOnRefreshListener, View.OnClickListener {
    View contentView;

    SHSwipeRefreshLayout mSHSwipeRefreshLayout;
    SHListView mSHListView;
    private List<ZsyjhBean.RowsBean> mList;
    SHListViewAdapter mSHListViewAdapter;
    ZsyjhSearchView mSearchView;

    private TextView mFootTextView;
    //head按钮
    private TextView leftTextView, prev, centerTextView, next, rightTextView;
    //数据加载分页数据
    private int pageNumber = 0;
    SearchBean mSearchBean;
    ZsyjhBean mZsyjhBean;
    public static boolean onStartRefresh = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_zsyjh, container, false);
        mSHSwipeRefreshLayout = (SHSwipeRefreshLayout) contentView.findViewById(R.id.SHSwipeRefreshLayout);
        mSHListView = (SHListView) contentView.findViewById(R.id.SHListView);
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        mSHSwipeRefreshLayout.setFooterView(FootView);
        mSearchView = (ZsyjhSearchView) contentView.findViewById(R.id.zsjhsearchview);

        leftTextView = (TextView) contentView.findViewById(R.id.leftTextView);
        prev = (TextView) contentView.findViewById(R.id.prev);
        centerTextView = (TextView) contentView.findViewById(R.id.centerTextView);
        next = (TextView) contentView.findViewById(R.id.next);
        rightTextView = (TextView) contentView.findViewById(R.id.rightTextView);


        InitData();
        initSearchView();
        InitListen();
        return contentView;
    }


    @Override
    protected void InitData() {
        //初始化工具栏
        mList = new ArrayList<>();
        mSHListViewAdapter = new SHListViewAdapter();
        mSHListView.setAdapter(mSHListViewAdapter);


    }

    private void initSearchView() {
        prev.setText("上一月");
        next.setText("下一月");

        mSearchBean = new SearchBean();
        //初始化搜索条件，开始日期为当月
        mSearchBean.setKsrq(DateUtil.getYearAndMonth(date));
        //初始化搜索条件，结束日期为当月
        mSearchBean.setJsrq(DateUtil.getYearAndMonth(date));
        centerTextView.setText(DateUtil.getYearAndMonth(date));

        mSearchView.setConfirmListener(new ZsyjhSearchView.OnClick() {
            @Override
            public void onConfirmListener(SearchBean Util) {
                mSearchBean = Util;
                mSHSwipeRefreshLayout.startRefresh();
                requestData(0, 10, "refresh"); //展示最新数据
            }
        });
    }


    @Override
    protected void InitListen() {
        mSHSwipeRefreshLayout.setOnRefreshListener(this);
        rightTextView.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
        prev.setOnClickListener(this);
        next.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftTextView:
                getActivity().finish();
                break;
            case R.id.rightTextView:
                if (mSearchView.getVisibility() == View.GONE) {
                    mSearchView.setVisibility(View.VISIBLE);
                } else {
                    mSearchView.setVisibility(View.GONE);
                }
                break;
            case R.id.prev:
                butPrev();
                break;
            case R.id.next:
                butNext();
                break;

        }
    }

    //按钮上个月事件
    public void butPrev() {
        date = DateUtil.getAfterMonthDate(date, -1);
        setSearchBean();
        upDatedAndRefresh(date);
    }

    //按钮下个月事件
    public void butNext() {
        date = DateUtil.getAfterMonthDate(date, 1);
        setSearchBean();
        upDatedAndRefresh(date);
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh(Date date) {
        centerTextView.setText(DateUtil.getYearAndMonth(date));
        //刷新列表数据
        onRefresh();
    }

    //    //设置搜索日期
    private void setSearchBean() {
        mSearchBean.setKsrq(DateUtil.getYearAndMonth(date));
        mSearchBean.setJsrq(DateUtil.getYearAndMonth(date));
        //将搜索数据同步更新带搜索view当中
        mSearchView.setDefualtdata(mSearchBean);
    }

    //页面第一次进入加载
    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        requestData(0, 10, ""); //初始化数据
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            requestData(0, 10, "refresh"); //初始化数据
            onStartRefresh = false;
        }
    }

    //网络请求数据
    private void requestData(int pageNum, int pageSize, final String flag) {
        this.pageNumber = pageNum;
        pageNumber++;
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("searchXdLx", "1");
        setParams(map,mSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getZsyjhList(map, new BaseCallBack<ZsyjhBean>() {
                    @Override
                    public void Success(Call<ZsyjhBean> call, Response<ZsyjhBean> response) {
                        try {
                            mZsyjhBean = response.body();
                            if (mZsyjhBean.getMsg().equals("success")) {
                                if (mZsyjhBean.getRows().size() > 0) {
                                    if (flag.equals("refresh")) { //判断是否是刷新，如果是刷新则将之前的List清空
                                        mList.clear();
                                    }
                                    mList.addAll(mZsyjhBean.getRows()); //将请求到的数据添加到List集合中
                                    mSHListViewAdapter.notifyDataSetChanged(); //刷新数据列表
                                } else {
                                    if (flag.equals("loadmore")) {
//                                        MyToast.showToast("暂无更多数据");
                                    } else {
                                        mList.clear();
                                        mSHListViewAdapter.notifyDataSetChanged();
//                                        MyToast.showToast("暂无数据");
                                    }
                                }
                            } else {
                                MyToast.showNullObjectError(getContext());
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<ZsyjhBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        switch (flag) {
                            case "refresh": //刷新
                                mSHSwipeRefreshLayout.finishRefresh();
                                break;
                            case "loadmore": //加载
                                mSHSwipeRefreshLayout.finishLoadmore();
                                break;
                        }
                    }
                }
        );
    }


    @Override
    public void onRefresh() {
        requestData(0, 10, "refresh");
    }

    @Override
    public void onLoading() {
        requestData(pageNumber, 10, "loadmore");
    }

    @Override
    public void onRefreshPulStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("下拉刷新");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("松开刷新");
                break;
            case SHSwipeRefreshLayout.START:
                mSHSwipeRefreshLayout.setRefreshViewText("正在刷新");
                break;
        }
    }

    @Override
    public void onLoadmorePullStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mFootTextView.setText("上拉加载");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mFootTextView.setText("松开加载");
                break;
            case SHSwipeRefreshLayout.START:
                mFootTextView.setText("正在加载...");
                break;
        }
    }

    private class SHListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder mViewHolder;
            if (convertView == null) {
                mViewHolder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_zsyjh, null);
                mViewHolder.yjhh = (TextView) convertView.findViewById(R.id.yjhh);
                mViewHolder.sgrq = (TextView) convertView.findViewById(R.id.sgrq);
                mViewHolder.lb = (TextView) convertView.findViewById(R.id.lb);
                mViewHolder.layout_blfh = (LinearLayout) convertView.findViewById(R.id.layout_blfh);
                mViewHolder.xm = (TextView) convertView.findViewById(R.id.xm);
                mViewHolder.hb = (TextView) convertView.findViewById(R.id.hb);
                mViewHolder.sgdd = (TextView) convertView.findViewById(R.id.sgdd);
                mViewHolder.sgxm = (TextView) convertView.findViewById(R.id.sgxm);
                mViewHolder.sgnr = (TextView) convertView.findViewById(R.id.sgnr);
                mViewHolder.sgjx = (TextView) convertView.findViewById(R.id.sgjx);
                mViewHolder.blfh = (TextView) convertView.findViewById(R.id.blfh);
                mViewHolder.sgdw = (TextView) convertView.findViewById(R.id.sgdw);
                mViewHolder.tablelayout = (LinearLayout) convertView.findViewById(R.id.tablelayout);
                mViewHolder.zt_layout = (LinearLayout) convertView.findViewById(R.id.zt_layout);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.yjhh.setText(mList.get(position).getBh());
            mViewHolder.sgrq.setText(mList.get(position).getExsgrq());
            mViewHolder.lb.setText(mList.get(position).getLb() + "类");
            if (mList.get(position).getLb().equals("B")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (mList.get(position).getLb().equals("C")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextC));
            }
            mViewHolder.xm.setText(mList.get(position).getXlmc());
            mViewHolder.hb.setText(mList.get(position).getXbmc());
            mViewHolder.sgdd.setText(mList.get(position).getSgdd());
            mViewHolder.sgxm.setText(mList.get(position).getXmmc());
            mViewHolder.sgnr.setText(mList.get(position).getNrmc());
            mViewHolder.sgjx.setText(mList.get(position).getJxmc());
            mViewHolder.blfh.setText(mList.get(position).getFhcsmc());
            mViewHolder.sgdw.setText(mList.get(position).getSgdwmc());
            mViewHolder.tablelayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Map<String, String> map = new HashMap<>();
                    map.put("bh", mList.get(position).getBh());


                    MyApplication.ShowWaitDialog(getContext());
                    NetWorkApi.getZsyjhXx(map, new Callback<ShyjhxqBean>() {
                                @Override
                                public void onResponse(Call<ShyjhxqBean> call, Response<ShyjhxqBean> response) {
                                    try {
                                        ShyjhxqBean Bean = response.body();
                                        ZsyjhChaKanActivity.ZsyjhxxBean = Bean;
                                        getContext().startActivity(new Intent(getContext(), ZsyjhChaKanActivity.class));
                                    } catch (Exception e) {
                                        MyToast.showFail();
                                    }
                                    MyApplication.HideWaitDialog();
                                }

                                @Override
                                public void onFailure(Call<ShyjhxqBean> call, Throwable t) {
                                    MyToast.showFail();
                                }
                            }
                    );
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        LinearLayout view;
        LinearLayout tablelayout;
        //月计划号
        TextView yjhh;
        //施工日期
        TextView sgrq;
        //类别
        TextView lb;
        //线名
        TextView xm;
        //行别
        TextView hb;
        //施工地点
        TextView sgdd;
        //施工项目
        TextView sgxm;
        //施工内容
        TextView sgnr;
        //施工机械
        TextView sgjx;
        //B类防护
        TextView blfh;
        //施工单位
        TextView sgdw;
        //状态
        TextView zt;

        LinearLayout zt_layout;

        //B类防御layout
        LinearLayout layout_blfh;
    }

    @Override
    public boolean onBackPressed() {
        if (mSearchView.getVisibility() == View.VISIBLE) {
            mSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    public Map<String,String> setParams(Map<String,String> map, SearchBean Bean) {
        if (Bean != null) {
            if (Bean.getLb() != null && !Bean.getLb().equals("")) {
                map.put("searchSgLb", mSearchBean.getLb());
            }
            if (Bean.getJhh() != null && !Bean.getJhh().equals("")) {
                map.put("searchBh", mSearchBean.getJhh());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", mSearchBean.getXm());
            }
            if (Bean.getDwhbmid() != null && !Bean.getDwhbmid().equals("")) {
//                if (!MyApplication.getmLoginUser().getUserUnitType().equals("sgb") && !MyApplication.getmLoginUser().getUserUnitType().equals("jgcs"))
                map.put("searchDwId", mSearchBean.getDwhbmid());
            }
            if (Bean.getKsrq() != null && !Bean.getKsrq().equals("")) {
                map.put("searchStartMonth", mSearchBean.getKsrq());
            }
            if (Bean.getJsrq() != null && !Bean.getJsrq().equals("")) {
                map.put("searchEndMonth", mSearchBean.getJsrq());
            }
        }
        return map;
    }

}
